/**
 * 全局Print模块
 * 提供简洁的API用于日志打印
 */

import Logger from './Logger'

class PrintManager {
  constructor() {
    this.logger = null
    this.defaultConfig = {
      serverUrl: 'http://192.168.1.100:3000',
      enableRemoteLogging: true,
      enableConsoleLogging: true,
      maxLocalLogs: 1000,
      autoSendInterval: 0,
    }
  }

  /**
   * 初始化Logger
   */
  init(config = {}) {
    this.logger = new Logger({ ...this.defaultConfig, ...config })
    return this
  }

  /**
   * 确保Logger已初始化
   */
  _ensureLogger() {
    if (!this.logger) {
      this.init()
    }
    return this.logger
  }

  /**
   * 基础打印方法
   */
  log(...messages) {
    return this._ensureLogger().log(...messages)
  }

  /**
   * 信息日志
   */
  info(...messages) {
    return this._ensureLogger().info(...messages)
  }

  /**
   * 调试日志
   */
  debug(...messages) {
    return this._ensureLogger().debug(...messages)
  }

  /**
   * 警告日志
   */
  warn(...messages) {
    return this._ensureLogger().warn(...messages)
  }

  /**
   * 错误日志
   */
  error(...messages) {
    return this._ensureLogger().error(...messages)
  }

  /**
   * 表格打印（对象数组）
   */
  table(data, title = 'Table') {
    if (!Array.isArray(data)) {
      return this.error('Table data must be an array')
    }

    const tableData = {
      title,
      type: 'table',
      data,
      count: data.length,
    }

    return this._ensureLogger().info('📊', title, tableData)
  }

  /**
   * JSON格式打印
   */
  json(obj, title = 'JSON') {
    const jsonData = {
      title,
      type: 'json',
      data: obj,
    }

    return this._ensureLogger().info('📝', title, jsonData)
  }

  /**
   * 网络请求日志
   */
  network(method, url, data = null, response = null) {
    const networkLog = {
      type: 'network',
      method: method.toUpperCase(),
      url,
      timestamp: new Date().toISOString(),
      request: data,
      response,
    }

    return this._ensureLogger().info('🌐', `${method.toUpperCase()} ${url}`, networkLog)
  }

  /**
   * 性能日志
   */
  performance(label, duration) {
    const perfLog = {
      type: 'performance',
      label,
      duration: `${duration}ms`,
      timestamp: new Date().toISOString(),
    }

    return this._ensureLogger().info('⚡', `Performance: ${label}`, perfLog)
  }

  /**
   * 用户行为日志
   */
  userAction(action, details = {}) {
    const actionLog = {
      type: 'user_action',
      action,
      details,
      timestamp: new Date().toISOString(),
    }

    return this._ensureLogger().info('👤', `User Action: ${action}`, actionLog)
  }

  /**
   * 分组开始
   */
  group(label) {
    return this._ensureLogger().info('📁', `GROUP START: ${label}`, { type: 'group_start', label })
  }

  /**
   * 分组结束
   */
  groupEnd(label) {
    return this._ensureLogger().info('📁', `GROUP END: ${label}`, { type: 'group_end', label })
  }

  /**
   * 计时开始
   */
  time(label) {
    if (!this._timers) {
      this._timers = new Map()
    }
    this._timers.set(label, Date.now())
    return this._ensureLogger().info('⏱️', `Timer started: ${label}`)
  }

  /**
   * 计时结束
   */
  timeEnd(label) {
    if (!this._timers || !this._timers.has(label)) {
      return this._ensureLogger().warn('⏱️', `Timer "${label}" not found`)
    }

    const startTime = this._timers.get(label)
    const duration = Date.now() - startTime
    this._timers.delete(label)

    return this.performance(label, duration)
  }

  /**
   * 断言日志
   */
  assert(condition, message, ...args) {
    if (!condition) {
      return this._ensureLogger().error('❌', `Assertion failed: ${message}`, ...args)
    }
    return this._ensureLogger().debug('✅', `Assertion passed: ${message}`)
  }

  /**
   * 清空日志
   */
  clear() {
    return this._ensureLogger().clear()
  }

  /**
   * 清空本地日志
   */
  clearLocal() {
    return this._ensureLogger().clearLocal()
  }

  /**
   * 获取本地日志
   */
  getLogs(level = null) {
    return this._ensureLogger().getLocalLogs(level)
  }

  /**
   * 获取连接状态
   */
  getStatus() {
    return this._ensureLogger().getConnectionStatus()
  }

  /**
   * 更新配置
   */
  updateConfig(config) {
    return this._ensureLogger().updateConfig(config)
  }

  /**
   * 手动刷新发送队列
   */
  flush() {
    return this._ensureLogger().flushQueue()
  }

  /**
   * 获取Logger实例（高级用法）
   */
  getLogger() {
    return this._ensureLogger()
  }
}

// 创建全局实例
const Print = new PrintManager()

// 导出单例
export default Print

// 同时导出类，支持多实例
export { PrintManager }


